<template>
  <div class="clientType">
    <div class="title-container">
      <div class="left-box">
        <el-form ref="form" :model="searchForm" :inline="true" class="formClass">
          <el-form-item>
            <el-input
              prefix-icon="el-icon-search"
              type="input"
              placeholder="请输入商品名称"
              clearable
              style="margin-right: 10px;"
              @clear="clearSearch"
              v-model="searchForm.productName"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <global-card>
      <template #leftTitle>
        <perButton label="新建奢侈品" type="primary" icon="el-icon-plus" perms="PROTOCOL_ADD"
                   @click="newCompanyClick"></perButton>
        <el-button type="success" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </template>
      <template #content>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          class="elTable"
        >
          <el-table-column type="index" label="序号" width="80" align="center"/>
          <el-table-column prop="" label="奢侈品照片" align="center">
            <template #default="{ row }">
              <viewer>
                <img
                  style="display: inline-block;height: 50px;width: 65px;"
                  :src="row.headUrl1.split('&')[0]"
                  class="mt-1 mr-1 ml-1 mb-1 bg-light h-100 w-100 obj-cover">
              </viewer>
            </template>
          </el-table-column>
          <el-table-column prop="productCode" label="奢侈品编码" align="center"/>
          <el-table-column prop="productName" label="奢侈品名称" align="center"/>
          <el-table-column prop="brandName" label="奢侈品品牌" align="center"/>
          <el-table-column prop="productPrice" label="价格" align="center"/>
          <el-table-column prop="" label="属性" align="center">
            <template slot-scope="scope">
              {{ proudctAttributeList[scope.row.productAsttributes].name}}
            </template>
          </el-table-column>
          <el-table-column prop="productStock" label="数量" align="center"/>
          <el-table-column prop="productDealNum" label="成交数量 " align="center"/>
          <el-table-column label="操作" width="300" align="center">
            <template #default="{ row }">
              <perButton label="配置折扣 " type="primary" size="mini" perms="PROTOCOL_ADD"
                         @click="configClick(row)"></perButton>
              <perButton label="编辑" type="warning" size="mini" perms="PROTOCOL_EDIT"
                         @click="handlerEdit(row)"></perButton>
              <perButton label="删除" type="danger" size="mini" perms="PROTOCOL_DEL"
                         @click="handlerDelete(row)"></perButton>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <pagination
          class="pagination"
          :total="count"
          :page.sync="pageIndex"
          :limit.sync="pageSize"
          @pagination="pagination"
        />
      </template>
    </global-card>

    <!-- 新增编辑 -->
    <yc-dialog
      ref="ycDialog"
      :dialogTitle="dialogTitle"
      :centerTitle="dialogCenterTitle"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            :model="newModel"
            :rules="rules"
            ref="newModelRef"
            label-width="110px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="奢侈品名称" prop="productName">
                  <el-input v-model="newModel.productName"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奢侈品品牌" prop="brandName">
                  <el-input v-model="newModel.brandName"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="奢侈品价格" prop="productPrice">
                  <el-input v-model="newModel.productPrice"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="奢侈品数量" prop="productStock">
                  <el-input v-model="newModel.productStock"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="成交数量" prop="productDealNum">
                  <el-input v-model="newModel.productDealNum"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="属性" prop="productAsttributes">
                  <el-select v-model="newModel.productAsttributes">
                    <el-option
                      v-for="item in proudctAttributeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="推荐分类" prop="hotType">
                  <el-radio-group v-model="newModel.hotType">
                    <el-radio :label="0">平台推荐商品</el-radio>
                    <el-radio :label="1">用户热门商品</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="详情图片" prop="detailUrl">
                  <div :class="detailsDisabled ? 'editor-container' : ''">
                    <dropzone
                      id="myVueDropzone2"
                      v-model="newModel.detailUrl"
                      :url="$uploadUrl + upload"
                      :thumbnailHeight="100"
                      :thumbnailWidth="100"
                      :defaultImg="imgList2"
                      :acceptedFiles="'image/jpeg,image/png'"
                      @dropzone-removedFile="dropzoneR2"
                      @dropzone-success="dropzoneS2"/>
                  </div>
<!--                  <el-upload-->
<!--                    :action="$uploadUrl + upload"-->
<!--                    class="avatar-uploader"-->
<!--                    v-model="newModel.detailUrl"-->
<!--                    :headers="headers"-->
<!--                    :show-file-list="false"-->
<!--                    :on-success="handleLogoSuccess"-->
<!--                    :before-upload="beforeAvatarUpload"-->
<!--                  >-->
<!--                    <img-->
<!--                      v-if="newModel.detailUrl"-->
<!--                      :src="newModel.detailUrl"-->
<!--                      class="avatar"-->
<!--                    />-->
<!--                    <i-->
<!--                      v-else-->
<!--                      class="el-icon-plus avatar-uploader-icon"-->
<!--                      :class="{ drop: detailsDisabled }"-->
<!--                    ></i>-->
<!--                  </el-upload>-->
                </el-form-item>
              </el-col>
<!--              <el-col :span="12">-->
<!--                <el-form-item label="奢侈品视频" prop="headVideoUrl">-->
<!--                  <el-upload-->
<!--                    v-model="newModel.headVideoUrl"-->
<!--                    class="avatar-uploader"-->
<!--                    accept="video/mp4,video/ogg,video/flv,video/avi,video/wmv,video/rmvb,video/mov"-->
<!--                    :action="$uploadUrl + upload"-->
<!--                    :headers="headers"-->
<!--                    :on-progress="uploadVideoProcess"-->
<!--                    :on-success="handleVideoSuccess"-->
<!--                    :before-upload="beforeUploadVideo"-->
<!--                    :show-file-list="false"-->
<!--                  >-->
<!--                    <video-->
<!--                      v-if="newModel.headVideoUrl != '' && !videoFlag"-->
<!--                      :src="newModel.headVideoUrl"-->
<!--                      class="avatar video-avatar"-->
<!--                      controls="controls">-->
<!--                      您的浏览器不支持视频播放-->
<!--                    </video>-->
<!--                    <i v-else-if="newModel.headVideoUrl == '' && !videoFlag"-->
<!--                       class="el-icon-plus avatar-uploader-icon"-->
<!--                    ></i>-->
<!--                    <el-progress v-if="videoFlag == true" type="circle"-->
<!--                                 :percentage="videoUploadPercent"-->
<!--                                 style="margin-top: 7px"></el-progress>-->
<!--                  </el-upload>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="奢侈品照片" prop="headUrl1">
                  <div :class="detailsDisabled ? 'editor-container' : ''">
                    <dropzone
                      id="myVueDropzone"
                      v-model="newModel.headUrl1"
                      :url="$uploadUrl + upload"
                      :thumbnailHeight="100"
                      :thumbnailWidth="100"
                      :defaultImg="imgList"
                      :acceptedFiles="'image/jpeg,image/png'"
                      @dropzone-removedFile="dropzoneR"
                      @dropzone-success="dropzoneS"/>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="奢侈品视频" prop="headVideoUrl">
                  <el-upload
                    v-model="newModel.headVideoUrl"
                    class="avatar-uploader"
                    accept="video/mp4,video/ogg,video/flv,video/avi,video/wmv,video/rmvb,video/mov"
                    :action="$uploadUrl + upload"
                    :headers="headers"
                    :on-progress="uploadVideoProcess"
                    :on-success="handleVideoSuccess"
                    :before-upload="beforeUploadVideo"
                    :show-file-list="false"
                  >
                    <video
                      v-if="newModel.headVideoUrl != '' && !videoFlag"
                      :src="newModel.headVideoUrl"
                      class="avatar video-avatar"
                      controls="controls">
                      您的浏览器不支持视频播放
                    </video>
                    <i v-else-if="newModel.headVideoUrl == '' && !videoFlag"
                       class="el-icon-plus avatar-uploader-icon"
                    ></i>
                    <el-progress v-if="videoFlag == true" type="circle"
                                 :percentage="videoUploadPercent"
                                 style="margin-top: 7px"></el-progress>
                  </el-upload>
                  <div v-if="newModel.headVideoUrl != '' && !videoFlag"
                       @click="deleteVideo()"
                       class="d-flex justify-content-center align-center"
                       style="margin-top: -15px;width: 195px;cursor: pointer;">删除
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 配置折扣 -->
    <yc-dialog
      ref="configDialog"
      :dialogTitle="dialogTitle"
      :centerTitle="dialogCenterTitle"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            :model="dataForm"
            :rules="dataRules"
            ref="dataForm"
            label-width="100px"
          >
            <el-form-item v-for="(item, index) in dataForm.configList"
                          :key="item.ruleCode"
                          :label="item.ruleName"
                          :prop="'configList.'+index+'.disCount'"
                          :rules="{
                             required: true, message: '请输入维修内容', trigger: 'blur'
                          }"
            >
              <el-input v-model="item.disCount"/>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogConfigSave">确定</el-button>
        <el-button @click="$refs.configDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import Dropzone from "@/components/Dropzone"
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryPageProduct,
    insertProduct,
    updateProduct,
    deleteProduct,
    queryRuleList,
    setProductDiscount, queryRuleListByProd
  } from "@/api/commodityInformation/carInfo"
  import { getToken } from "@/utils/auth"

  export default {
    components: {
      Dropzone,
      ycDialog,
      perButton
    },
    data() {
      return {
        tableData: [],
        pageIndex: 1,
        pageSize: 10,
        count: 0,
        searchForm: {
          productName: ""
        },

        detailsDisabled: false,
        isGlobalMessageShow: false,

        dialogCenterTitle: "",
        dialogTitle: "",
        message: "",

        loading: false,
        newModel: {
          id: "",
          productCode: "",
          productName: "",
          brandName: "",
          // milage: "",
          // vehicleModel: "",
          productAsttributes: "",
          productPrice: "",
          productDealNum: "",
          productStock: "",
          hotType: "",
          detailUrl: "",
          headVideoUrl: "",
          headUrl1: ""
        },
        rules: {
          productName: [
            { required: true, message: "请输入奢侈品名称", trigger: "blur" }
          ],
          brandName: [
            { required: true, message: "请输入奢侈品品牌", trigger: "blur" }
          ],
          // milage: [
          //   { required: true, message: "请输入里程数", trigger: "blur" }
          // ],
          // vehicleModel: [
          //   { required: true, message: "请输入车辆型号", trigger: "blur" }
          // ],
          productAsttributes: [
            { required: true, message: "请选择属性", trigger: "change" }
          ],
          productPrice: [
            { required: true, message: "请输入奢侈品价格", trigger: "blur" }
          ],
          productDealNum: [
            { required: true, message: "请输入成交数量", trigger: "blur" }
          ],
          productStock: [
            { required: true, message: "请输入奢侈品数量", trigger: "blur" }
          ],
          hotType: [
            { required: true, message: "请选择推荐分类", trigger: "change" }
          ]
        },
        proudctAttributeList: [
          { id: 0, name: "在线购买" },
          { id: 1, name: " 预约查看" }
        ],
        headers: {
          token: getToken()
        },
        upload: "/uploadManager/upload",
        videoFlag: false,
        //是否显示进度条
        videoUploadPercent: "",
        //进度条的进度，
        isShowUploadVideo: false,
        //显示上传按钮
        videoForm: {
          showVideoPath: ""  //回显的变量
        },
        userData: [],
        imgList: [],
        imgList2: [],

        dataForm: {
          configList: []
        },
        dataRules: {
          // disCount: [
          //   { required: true, message: "请输入内容", trigger: "blur" }
          // ]
        },
        addOrUpdateLoading: false
      }
    },
    created() {
      this.getData()
    },
    methods: {
      async searchClick() {
        this.getData()
      },
      clearSearch() {
        this.getData()
      },
      async getData() {
        const { productName } = this.searchForm
        this.loading = true
        const data = await queryPageProduct({
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          productType: "2",
          investmentType: 0,
          productName
        })
        this.tableData = data.object.data
        this.count = data.object.count
        this.loading = false
      },
      pagination(pageItem) {
        this.getData(pageItem.page, pageItem.limit)
      },


      handlerDelete({ id }) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { status } = await deleteProduct({
            id
          })
          if (status == 200) {
            this.getData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      // 新建奢侈品
      newCompanyClick() {
        this.dialogCenterTitle = "新建奢侈品"
        this.dialogTitle = "新建奢侈品"
        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true

        if (this.$refs["newModelRef"]) {
          this.$refs["newModelRef"].clearValidate()
        }
        Object.keys(this.newModel).forEach((item) => {
          this.newModel[item] = ""
        })
        this.imgList = []
        this.imgList2 = []
      },

      handlerEdit(row) {
        this.dialogCenterTitle = "编辑奢侈品"
        this.dialogTitle = "编辑奢侈品"

        this.newModel = {
          id: row.id,
          productCode: row.productCode,
          productName: row.productName,
          brandName: row.brandName,
          productAsttributes: row.productAsttributes,
          productPrice: row.productPrice,
          productStock: row.productStock,
          productDealNum: row.productDealNum,
          hotType: row.hotType,
          detailUrl: row.detailUrl,
          headVideoUrl: row.headVideoUrl,
          headUrl1: row.headUrl1
        }

        if (row.detailUrl) {
          this.imgList2 = row.detailUrl.split("&")
        }
        if (row.headUrl1) {
          this.imgList = row.headUrl1.split("&")
        }

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs["newModelRef"]) {
          this.$refs["newModelRef"].clearValidate()
        }
      },

      handleLogoSuccess(id, file) {
        this.newModel.detailUrl = file.response.object.url
      },
      beforeAvatarUpload(file) {
        // const isType = this.fileType.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 5

        // if (!isJPG) {
        //   this.$message.error("上传头像图片只能是 JPG 格式!")
        // }
        // if (!isType) {
        //   this.$message.error("上传文件格式有问题！")
        // }
        // if (!isLt2M) {
        //   this.$message.error("上传头像图片大小不能超过 5MB!")
        // }
        // return isJPG && isLt2M
        // return isType && isLt2M
      },

      //上传前回调
      beforeUploadVideo(file) {
        var fileSize = file.size / 1024 / 1024 < 50   //控制大小  修改50的值即可
        if (
          [
            "video/mp4",
            "video/ogg",
            "video/flv",
            "video/avi",
            "video/wmv",
            "video/rmvb",
            "video/mov"
          ].indexOf(file.type) == -1     //控制格式
        ) {
          this.$message.warning("请上传正确的视频格式")
          return false
        }
        if (!fileSize) {
          this.$message.warning("视频大小不能超过50MB")
          return false
        }
        this.isShowUploadVideo = false
      },
      //进度条
      uploadVideoProcess(event, file, fileList) {    //注意在data中添加对应的变量名
        this.videoFlag = true
        this.videoUploadPercent = file.percentage.toFixed(0) * 1
      },
      //上传成功回调
      handleVideoSuccess(res, file) {
        this.isShowUploadVideo = true
        this.videoFlag = false
        this.videoUploadPercent = 0

        console.log(res)
        //后台上传数据
        if (res.success == true) {
          this.newModel.headVideoUrl = res.object.url    //上传成功后端返回视频地址 回显
        } else {
          this.$message.error("上传失败！")
        }
      },

      deleteVideo() {
        this.newModel.headVideoUrl = ""
        this.videoFlag = false
        this.isShowUploadVideo = false
        this.videoUploadPercent = 0
      },

      dropzoneS(file) {
        const res = JSON.parse(file.xhr.response)
        this.imgList.push(res.object.url)
        this.newModel.headUrl1 = this.imgList.join("&")
      },
      dropzoneR(file) {
        let res
        let index
        if (file.xhr) {
          res = JSON.parse(file.xhr.response)
          index = this.imgList.findIndex(item => item == res.object.url)
        } else {
          res = file.url
          index = this.imgList.findIndex(item => item == res)
        }
        this.imgList.splice(index, 1)
        this.newModel.headUrl1 = this.imgList.join("&")
      },
      dropzoneS2(file) {
        const res = JSON.parse(file.xhr.response)
        this.imgList2.push(res.object.url)
        this.newModel.detailUrl = this.imgList2.join("&")
      },
      dropzoneR2(file) {
        let res
        let index
        if (file.xhr) {
          res = JSON.parse(file.xhr.response)
          index = this.imgList2.findIndex(item => item == res.object.url)
        } else {
          res = file.url
          index = this.imgList2.findIndex(item => item == res)
        }
        this.imgList2.splice(index, 1)
        this.newModel.detailUrl = this.imgList2.join("&")
      },

      async dialogSave() {
        this.$refs.newModelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true

            if (this.detailsDisabled) {
              // 详情
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newModel.id) {
              //  编辑
              const { status, message } = await updateProduct({
                ...this.newModel, productType: 2
              })
              if (status == 200) {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            } else {
              const { status, message } = await insertProduct({ ...this.newModel, productType: 2 })
              if (status == "200") {
                this.$message({
                  message: message,
                  type: "success"
                })
                this.getData()
                this.$refs.ycDialog.dialogVisible = false
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },


      // 配置折扣
      configClick(row) {
        this.dialogTitle = "配置折扣"
        this.dialogCenterTitle = "配置折扣"

        this.itemTableData = row
        this.queryRuleListByProd()

        this.$refs.configDialog.dialogVisible = true
      },
      queryRuleListByProd() {
        queryRuleListByProd({
          productCode: this.itemTableData.productCode
        }).then(res => {
          this.dataForm.configList = res.object ? res.object : []
        })
      },

      dialogConfigSave() {
        this.$refs.dataForm.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            const arr = this.dataForm.configList.map(item => {
              return {
                ruleCode: item.ruleCode,
                disCount: item.disCount,
                productCode: this.itemTableData.productCode
              }
            })
            const { status, message } = await setProductDiscount({
              ruleList: JSON.stringify(arr)
            })
            if (status == "200") {
              this.$message({
                message: message,
                type: "success"
              })
              this.getData()
              this.$refs.configDialog.dialogVisible = false
            }
            this.addOrUpdateLoading = false
          }
        })
      },


      receive() {
        this.isGlobalMessageShow = false
      },
      refresh() {
        this.searchForm = {
          agreementName: "",
          agreementType: ""
        }
        this.getData()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .clientType {
    .title-container {
      display: flex;
      justify-content: flex-end;
      margin-right: 20px;

      .left-box {
        display: flex;

        .formClass {
          /*display: flex;*/
          /*margin-right: 20px;*/

          .el-form-item {
            margin-top: 20px;
            margin-bottom: 0;

            .el-input {
              width: 216px;
            }

            .el-select {
              width: 171px;
              margin-left: 10px;
            }

            .el-date-editor {
              width: 336px;
              margin-left: 10px;
            }
          }
        }

        /*.el-button {*/
        /*  // width: 42px;*/
        /*  height: 36px;*/
        /*  margin-top: 20px;*/
        /*}*/
      }
    }
  }

  .editor-container {
    pointer-events: none;
    background-color: #C0C4CC !important;
    color: #C0C4CC !important;
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 195px;
    height: 195px;
    line-height: 195px;
    text-align: center;
    /* cursor: no-drop; */
  }

  .avatar {
    width: 195px;
    height: 195px;
    display: block;
  }

  .drop {
    cursor: no-drop;
  }
</style>
